﻿' Copyright © Microsoft Corporation.  All Rights Reserved.
' This code released under the terms of the 
' Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
Imports Microsoft.VisualBasic
Imports System
Imports System.Diagnostics
Imports System.Globalization
Imports System.IO.IsolatedStorage
Imports System.Windows
Imports System.Windows.Browser
Imports System.Windows.Controls
Imports System.Windows.Controls.Primitives

Namespace ExpressionMediaPlayer

	Partial Public Class OfflineDownloadProgressDialog
		Inherits UserControl
        Private _parent As Popup
        Private grid As Grid
        Private player As MediaPlayer

        ''' <summary>
        ''' The percentage of the current file that has been downloaded
        ''' </summary>
        Private privateDownloadPercent As Double
        Friend Property DownloadPercent() As Double
            Get
                Return privateDownloadPercent
            End Get
            Set(ByVal value As Double)
                privateDownloadPercent = value
            End Set
        End Property
        ''' <summary>
        ''' The total number of items to be downloaded
        ''' </summary>
        Private privateTotalItemCount As Integer
        Friend Property TotalItemCount() As Integer
            Get
                Return privateTotalItemCount
            End Get
            Set(ByVal value As Integer)
                privateTotalItemCount = value
            End Set
        End Property
        ''' <summary>
        ''' The current item just downloaded
        ''' </summary>
        Private privateCurrentItem As Integer
        Friend Property CurrentItem() As Integer
            Get
                Return privateCurrentItem
            End Get
            Set(ByVal value As Integer)
                privateCurrentItem = value
            End Set
        End Property
        ''' <summary>
        ''' The flag set when the user clicks the cancel button
        ''' </summary>
        Private privateCancelWasClicked As Boolean
        Friend Property CancelWasClicked() As Boolean
            Get
                Return privateCancelWasClicked
            End Get
            Private Set(ByVal value As Boolean)
                privateCancelWasClicked = value
            End Set
        End Property

        ''' <summary>
        ''' The flag set when the background thread encounters a error
        ''' </summary>
        Private privateErrorOccured As Boolean
        Friend Property ErrorOccured() As Boolean
            Get
                Return privateErrorOccured
            End Get
            Set(ByVal value As Boolean)
                privateErrorOccured = value
            End Set
        End Property

        ''' <summary>
        ''' The error message set when the background thread encounters a error
        ''' </summary>
        Private privateErrorMessage As String
        Friend Property ErrorMessage() As String
            Get
                Return privateErrorMessage
            End Get
            Set(ByVal value As String)
                privateErrorMessage = value
            End Set
        End Property

        Friend Sub New(ByVal player As MediaPlayer)
            InitializeComponent()
            Me.player = player
        End Sub

        ''' <summary>
        ''' Browser window resize event handler
        ''' </summary>
        Private Sub OnPluginSizeChanged(ByVal sender As Object, ByVal e As EventArgs)
            UpdateSize()
        End Sub

        ''' <summary>
        ''' Resizes the grid container -- effectively centering the dialog in the application window
        ''' </summary>
        Private Sub UpdateSize()
            Me.grid.Width = Application.Current.Host.Content.ActualWidth
            Me.grid.Height = Application.Current.Host.Content.ActualHeight
        End Sub

        ''' <summary>
        ''' Respond to the user clicking the cancel button
        ''' </summary> 
        Private Sub Click_CancelOfflineDownload(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Me.CancelWasClicked = True
            Me.butonCancelOfflineDownload.IsEnabled = False
            If Me.buttonCompleteInstallation.IsEnabled Then ' Download was completed -- the user is cancelling the final install
                Close()
            End If
            Me.player.SetOfflineButtonEnabled(True)
        End Sub

        ''' <summary>
        ''' Respond to the user clicking the finish installation button
        ''' </summary> 
        Private Sub Click_CompleteInstallation(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim installSuccess As Boolean = False
            Try
                ' actually take the app offline.
                installSuccess = Application.Current.Install()
                Debug.WriteLine("Application.Current.Install() result=" & installSuccess.ToString())
                If installSuccess Then
                    Me.player.SetOfflineButtonVisibility(Visibility.Collapsed)
                    Close()
                End If
            Catch exp As InvalidOperationException
                Debug.WriteLine("Exception attempting to install offline" & exp.ToString())
            End Try
            If Not installSuccess Then
                ' Failed for some reason -- let them try again ?
                Me.player.SetOfflineButtonEnabled(True)
            End If
        End Sub

        ''' <summary>
        ''' Displays this popup window
        ''' </summary>
        Friend Sub Show()
            If _parent Is Nothing Then
                _parent = New Popup()
                Me.grid = New Grid()
                grid.Children.Add(Me)
                _parent.Child = grid
                AddHandler Application.Current.Host.Content.Resized, AddressOf OnPluginSizeChanged
                _parent.IsOpen = True
                Me.buttonCompleteInstallation.IsEnabled = False
                UpdateSize()
            End If
        End Sub

        ''' <summary>
        ''' Shuts down this popup window
        ''' </summary>
        Friend Sub Close()
            If Me.CancelWasClicked Then
                IsolatedStorageFile.GetUserStoreForApplication().Remove() ' Zap all those files just downloaded.
            End If

            If _parent IsNot Nothing Then
                _parent.IsOpen = False
                RemoveHandler Application.Current.Host.Content.Resized, AddressOf OnPluginSizeChanged
                Me.grid.Children.Remove(Me)
                _parent.Child = Nothing
                _parent = Nothing
            End If
        End Sub

		''' <summary>
		''' downloading playlist
		''' </summary>
		''' <param name="sender"></param>
		''' <param name="e"></param>
		Friend Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As PlaylistDownloadProgressEventArgs)
			Me.DownloadPercent = e.Progress * 100.0
			Me.Dispatcher.BeginInvoke(Function() AnonymousMethod1())
		End Sub
		
		Private Function AnonymousMethod1() As Object
			UpdateUI()
			Return Nothing
		End Function

		''' <summary>
		''' Update the UI with the current progress status
		''' </summary>
		Friend Sub UpdateUI()
			Me.progressBarThisFile.Value = Me.DownloadPercent
			If Me.CurrentItem > Me.TotalItemCount Then
				Me.TotalItemCount = Me.CurrentItem
			End If
			Me.progressBarOfflining.Value = (100.0 * Me.CurrentItem) / Me.TotalItemCount
			Me.textBlockCount.Text = Me.CurrentItem.ToString(CultureInfo.CurrentCulture)
			Me.textBlockTotal.Text = Me.TotalItemCount.ToString(CultureInfo.CurrentCulture)
		End Sub

		''' <summary>
		''' Called downloader once all items have be downloaded.
		''' </summary> 
		Friend Sub DownloadCompletedSuccessfully()
			Me.progressBarOfflining.Value = 100
			Me.textBlockDownloading.Visibility = Visibility.Collapsed
			Me.textBlockPromptToFinish.Visibility = Visibility.Visible
			Me.buttonCompleteInstallation.IsEnabled = True
		End Sub

		Friend Sub ReportError(ByVal errorMessage As String)
			Me.ErrorOccured = True
			Me.ErrorMessage = errorMessage
			Me.Dispatcher.BeginInvoke(Function() AnonymousMethod2())
		End Sub
		
		Private Function AnonymousMethod2() As Object
			DisplayErrorOnUIThread()
			Return Nothing
		End Function

		Friend Sub DisplayErrorOnUIThread()
			If Me.ErrorOccured Then
				If Me.textBlockErrorMessage.Visibility <> Visibility.Visible Then
					Me.textBlockErrorMessage.Visibility = Visibility.Visible
					Me.textBlockErrorMessage.Text = Me.ErrorMessage
					Me.textBlockDownloading.Visibility = Visibility.Collapsed
					Me.textBlockDownloading.Visibility = Visibility.Collapsed
					Me.buttonCompleteInstallation.IsEnabled = False
				End If
			End If
		End Sub
	End Class
End Namespace
